
//
// 110221a- AH - Created.
// 110221b- AH - Fixed close action not named.
//

package org.soekrat.gui.swing;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
 * <p>
 *   Dialog to show error messages in.
 * </p>
 * @author Arne Halvorsen (AH)
 * @author Laetitia Le Chatton (LLC) 
 */
@SuppressWarnings("serial")
public final class ErrorDialog extends JDialog 
{
  private final JTextArea m_text=new JTextArea();
  
  /**
   * <p>
   *   Constructor.
   * </p>
   * @param p Dialog's parent.
   */
  public ErrorDialog(){ buildGui(); }
  
  /**
   * <p>
   *   Constructor.
   * </p>
   * @param p Dialog's parent.
   */
  public ErrorDialog(Frame p){ super(p); buildGui(); }
  
  /**
   * <p>
   *   Constructor.
   * </p>
   * @param p Dialog's parent.
   */
  public ErrorDialog(Dialog p){ super(p); buildGui(); }
  
  // Invoked from constructors.
  private void buildGui()
  {
    setTitle("Error");
    setModal(true);
    
    Container c=getContentPane();
    c.setLayout(new BorderLayout());
    
    m_text.setEditable(false);
    c.add(new JScrollPane(m_text), BorderLayout.CENTER);
    
    JPanel buttons=new JPanel(new FlowLayout(FlowLayout.CENTER));
    buttons.add
    (
      new JButton
      (
        new AbstractAction("Close")
        { 
          public void actionPerformed(ActionEvent e){ dispose(); }
        }
      )
    );
    c.add(buttons, BorderLayout.SOUTH);
    
    pack();
    setSize(400, 400);
  }
  
  /**
   * <p>
   *   Shows error message.
   * </p>
   * @param t Exception.
   */
  public void showDialog(Throwable t)
  {
    if (t==null)
    {
      throw new NullPointerException("t");
    }
    
    String msg=t.getLocalizedMessage();
    msg=(msg==null) ? "" : msg.trim();
    if (msg.length()==0) msg=t.getClass().getSimpleName();
    
    showDialog(msg);
  }
  
  /**
   * <p>
   *   Shows error message.
   * </p>
   * @param msg Message.
   */
  public void showDialog(String msg)
  {
    if (msg==null)
    {
      throw new NullPointerException("msg");
    }
    
    m_text.setText(msg);
    m_text.setCaretPosition(0);
    
    setVisible(true);
  }
  
  private final static ErrorDialog c_dlg=new ErrorDialog();
  
  /**
   * <p>
   *   Shows dialog.
   * </p>
   * @param t Exception.
   */
  public static void show(Throwable t){ c_dlg.showDialog(t); }
  
  /**
   * <p>
   *   Shows dialog.
   * </p>
   * @param msg Error message.
   */
  public static void show(String msg){ c_dlg.showDialog(msg); }
  
}
